import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import {Button, Table, Form, Badge, Popover, Alert} from 'antd';
import SlideFrame from 'components/slide-frame'
import CityGroupService from 'containers/setting/city-group/city-group.service';
import CityGroupSlideFrame from 'containers/setting/city-group/city-group-fields/city-group-slide-frame';
import {messages} from "share/common";
import ExportModal from "components/template/export-modal/export-modal";
import ImportModal from 'components/template/import-modal-ie/import-modal'
import config from 'config';
import ResizeTable from "components/resize-table";

class CityGroup extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      data: [],
      columns: [
        {title:  messages('setting.key181'/*名称*/), dataIndex: 'levelName',//名称
          render: (text) => {
            return (
              <Popover content={text}
                       placement="topLeft">
                {text}
              </Popover>
            )
        }},
        {title: messages('setting.key184'/*编码*/), dataIndex: 'code',//编码
          render: (text) => {
            return (
              <Popover content={text}
                       placement="topLeft">
                {text}
              </Popover>
            )
          }},
        {title: messages('setting.key186'/*描述*/), dataIndex: 'comment',
          render: (text) => {
            return (
              <Popover content={text}
                       placement="topLeft">
                {text}
              </Popover>
            )
          }},
        {title: messages('common.column.status'/*状态*/), dataIndex: 'deleted',
          render: ( text => {
            return (
              text ? <span><Badge status="error"/>{messages('common.status.disable')/*禁用*/}</span> :
                <span><Badge status="success"/>{messages('common.status.enable')/*启用*/}</span>
            )}
          )
        },
        {title: messages('common.operation')/*操作*/, dataIndex: 'operation', width: '10%',
          render: ((text, record) => {
            return (
              <div>
                {
                  record.deleted ?
                    <a onClick={(e) => this.onRecordEdit(e, record)} style={{fontSize: 13}}>
                      {messages('common.edit') /* 编辑 */}</a>
                :
                  <div>
                    <a onClick={(e) => this.onRecordEdit(e, record)} style={{fontSize: 13}}>
                      {messages('common.edit') /* 编辑 */}</a>&nbsp;
                    <a onClick={(e) => this.onRecordDetail(e, record)} style={{fontSize: 13}}>
                      {messages('setting.key202'/*详情*/)}</a>
                  </div>
                }
              </div>
            )}
          )
        },
      ],
      page: 0,
      pageSize: 10,
      pagination:{
        total: 0,
        page: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      record: {},//选择某一行进行编辑时的当前行
      visible: false,
      cityGroupDetail: menuRoute.getRouteItem('city-group-info','key').url,
      cityGroupAllot: menuRoute.getRouteItem('city-group-allot-company','key').url, //分配公司页面
      downLoadTempList: [],
      errorsList: [],
      transactionOID: null,
      fileUploading: false,
      progressImportErr: 1,
      showImportErr: false,
      uploading: false,
    };
  }

  componentWillMount () {
    this.getCityGroupList();
  };

  getCityGroupList = () => {
    let { pagination } = this.state;
    this.setState({
      loading: true,
    });
    CityGroupService.getCityGroupList(pagination.page, pagination.pageSize).then(
      res => {
        if(res.status === 200){
          pagination.total = Number(res.headers['x-total-count']);
          pagination.current = this.state.pagination.page + 1;
          this.setState({
            data: res.data,
            loading: false,
            pagination,
          });
        }
      }
    )
  };

  //点击新建城市组组
  newCityGroup = () => {
    this.setState({
      record: {},
    }, () => {
      this.showSlide(true)
    });
  };

  //点击每一行的编辑
  onRecordEdit = (e, record) => {
    e.stopPropagation();
    this.setState({
      record: record,
    }, () => {
      this.showSlide(true)
    });
  };

  handleRowClick = (record) => {
    this.onRecordDetail(null, record);
  };

  //点击每一行的详情
  onRecordDetail = (e, record) => {
    const { cityGroupDetail } = this.state;
    this.setState({
      record,
    }, () => {
      this.context.router.push({
        pathname: cityGroupDetail.replace(':levelOID', record.levelOID),
        state: {disabled: record.deleted},
      })
    });
  };

  afterCloseSlide = () => {
    this.getCityGroupList();
    this.showSlide(false);
  };

  showSlide = (flag) => {
    this.setState({
      visible: flag,
    })
  };

  //分页点击
  onTableChange = (pagination1) => {
    let { pagination } = this.state;
    pagination.page = pagination1.current - 1;
    pagination.pageSize = pagination1.pageSize;
    pagination.total = pagination1.total;
    this.setState({
      pagination,
    }, () => {
      this.getCityGroupList();
    })
  };

  render () {
    const {data, columns, pagination, record, visible, loading} = this.state;
    const downLinks = (
        <div>
         4. <a href={"http://cloudhelios-static.oss-cn-shanghai.aliyuncs.com/other/helios_city.xlsx"}>
            {messages('setting.key1747')/*下载《城市基本信息表》，导入城市的编码需与表中的编码一致*/}
          </a>
        </div>
    );
    let text = messages('setting.key2151')/*Q：1000个不够怎么办？A：地点所属城市组支持向上兼容；eg：若需要将中国所有地点设置为国内城市组，则可以直接将【中国】添加进该城市组*/;
    return(
      <div>
        <div style={{fontSize: 13}}>
          <Button type={'primary'}
                  style={{marginRight: 15}}
                  onClick={this.newCityGroup}>
            {messages('setting.key203'/*新建城市组*/)}
          </Button>
          <ImportModal
            downLinks={downLinks}
            hasErrInfo={true}
            uploadUrl={`${config.baseUrl}/api/level/import/v2?${this.props.tenantMode ? 'roleType=TENANT' : ""}`}
            showErrUrl={`${config.baseUrl}` + "/api/batch/transaction/logs/v2/${transactionOID}"}
            exportErrUrl={`${config.baseUrl}` + "/api/level/error/export?transactionOID=${transactionOID}"}
            onCancel={this.getCityGroupList}
            templates={[{
                         downloadName: messages('setting.key1800')/*下载城市级别导入模板*/,
                         templateName: messages('setting.key1743')/*城市级别导入模板*/,
                         downloadUrl: "/api/level/template",
                         downloading: "cityLoading"
                       }]}
          />
          &nbsp; &nbsp; &nbsp;
          <div style={{display: "inline-block"}}>
          <ExportModal
            codeCheck={true}
            exportTitle={<Button>{messages('setting.key1745')/*导出*/}</Button>}
            exportType="CITY_LEVEL"
            exportCondition={{"tenantId": this.props.user.tenantId}}
            exportCommand={"CITY_LEVEL"}/>
          </div>
          {/*<Button type={'primary'}*/}
                  {/*disabled={!this.props.tenantMode}*/}
                  {/*onClick={() => {this.context.router.push(cityGroupAllot)}}>*/}
            {/*分配公司*/}
          {/*</Button>*/}
        </div>
        <br/>
        <Alert
          message={messages('setting.key2152')/*注意：每个城市组最多可添加1000个地点*/}
          description={text}
          type="info"
          showIcon
        />
        <div style={{fontSize: 13, margin: "15px 0 5px"}}>
          {messages('common.total', {total: pagination.total})}{/* 共 total 条数据 */}
        </div>
        <div className='city-group-table'>
          <ResizeTable
            bordered
            size={'middle'}
            rowKey={'id'}
            loading={loading}
            dataSource={data}
            columns={columns}
            onChange={this.onTableChange}
            pagination={pagination}
          />
        </div>
        <SlideFrame title={JSON.stringify(record) === '{}' ? messages('setting.key203'/*新建城市组*/) : messages('setting.key205'/*编辑城市组*/)}
                    show={visible}
                    content={CityGroupSlideFrame}
                    afterClose={this.afterCloseSlide}
                    onClose={() => this.showSlide(false)}
                    params={record}/>
      </div>
    )
  };
}

CityGroup.contextTypes = {
  router: React.PropTypes.object,
};
function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    language: state.main.language,
    company: state.login.company,
    user: state.login.user,
  }
}

const wrappedCityGroup = Form.create()(CityGroup);
export default connect(mapStateToProps)(wrappedCityGroup);
